#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash petsc-2.3.3.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

if [[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]]; then
    echo "请输入正确的构建路径"
    exit 1
fi
if [[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]]; then
    echo "请输入正确的安装路径"
    exit 1
fi

buildpath=$1
installpath=$2
if [[ "$1" =~ .*/$ ]]; then buildpath=${buildpath%/*}; fi
if [[ "$2" =~ .*/$ ]]; then installpath=${installpath%/*}; fi
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar cmake environment-modules
yum install git wget tcsh libgfortran-static make vim-common lapack-devel lapack-static blas-devel blas-static zlib-devel gcc-gfortran libX11-devel libXmu-devel mesa-libGL-devel freeglut-devel libXi-devel qt5-qtx11extras qt5-qtx11extras-devel -y

wget -t 10 -c -P $buildpath https://ftp.mcs.anl.gov/pub/petsc/release-snapshots/petsc-2.3.3.tar.gz
tar xf $buildpath/petsc-2.3.3.tar.gz -C $buildpath && rm -rf $buildpath/petsc-2.3.3.tar.gz
cd $buildpath/petsc-2.3.3-p16
sed -i '129s/^/#&/g'  ./config/configure.py
rm -rf python/BuildSystem/config/packages/config.guess python/BuildSystem/config/packages/config.sub
wget -t 10 -c http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess -P python/BuildSystem/config/packages
wget -t 10 -c http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub -P python/BuildSystem/config/packages
chmod +x python/BuildSystem/config/packages/config.guess python/BuildSystem/config/packages/config.sub
rm -rf bin/config/config.guess bin/config/config.sub
wget -t 10 -c http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.guess -P bin/config
wget -t 10 -c http://savannah.gnu.org/cgi-bin/viewcvs/*checkout*/config/config/config.sub -P bin/config
chmod +x bin/config/config.guess bin/config/config.sub
export PETSC_DIR=$PWD
./config/configure.py PETSC_ARCH=arm_install --prefix=$installpath/petsc --with-x=0
sed -i '19s/^/#&/g'  makefile
sed -i '24s/^/#&/g'  makefile
make all
make install
cp $installpath/petsc/lib/arm_install/* $installpath/petsc/lib/
cp $installpath/petsc/bmake/arm_install/* $installpath/petsc/include/
unset PETSC_DIR
cat >"$installpath/petsc/petsc_modulefiles" <<EOF
#%Module1.0
conflict petsc
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
        set modfile_path [file dirname \$modfile]
            return \$modfile_path
    }
set pwd [getModulefileDir]
set PETSC \$pwd
setenv PETSC \$PETSC
prepend-path PETSC_DIR \$PETSC
EOF
rm -rf $buildpath/petsc-2.3.3-p16
